package com.ruoyi.whzj.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.impl.SysNoticeServiceImpl;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;


/**
 * 快手接口控制器
 */
@Controller
@RequestMapping(value = "/phone/whzj/user")
public class WhUserPhoneController extends BaseController {

    @Autowired
    private IWhUserService whUserService;

    @Autowired
    private IWhTasksettingService whTasksettingService;

    @Autowired
    private IWhzjBaseconfigService whzjBaseconfigService;

    @Autowired
    private IWhBalancerecordService whBalancerecordService;

    @Autowired
    private IWhIntegralHistoryService whIntegralHistoryService;

    @Autowired
    private IWhUserwithdrawService whUserwithdrawService;

    @Autowired
    private IWhMemberlevelService whMemberlevelService;

    @Autowired
    private IWhPointspackageService whPointspackageService;

    @Autowired
    private IWhAskquestionService whAskquestionService;

    @Autowired
    private CommonRpc commonRpc;

    @Autowired
    private ISysNoticeService sysNoticeService;

    @Autowired
    private IWhVersionService whVersionService;

    @Autowired
    private IWhAutocommontService whAutocommontService;



    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    public AjaxResult getKuaiId(String userId)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if("0".equals(whUser.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        WhMemberlevel memberlevel = whMemberlevelService.selectMemberLevelByUserId(userId);
        if(whUser == null) {
            return error("用户不存在");
        }
        if(memberlevel == null){
            memberlevel = whMemberlevelService.selectWhMemberlevelById("875451589578441278");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user", whUser);
        map.put("nextLevel", memberlevel);
        return success("操作成功", map);
    }


    /**
     * 获取用户的邀请人数，以及需要多少人升级为代理
     * @param userId
     * @return
     */
    @RequestMapping("/getAutoRiselevel")
    @ResponseBody
    public AjaxResult getAutoRiselevel(String userId)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if("0".equals(whUser.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        List<WhUser> list = whUserService.selectWhUserByPCode(whUser.getInvitationCode());
        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        Map<String, String> map = new HashMap<>();
        map.put("yaoqingNum", String.valueOf(list.size()));
        map.put("auto", String.valueOf(whzjBaseconfig.getAutoRiselevel()));
        return success("操作成功", map);

    }



    /**
     * 代理数据
     * @param userId
     * @return
     */
    @RequestMapping("/getAgentNum")
    @ResponseBody
    public AjaxResult getAgentNum(String userId)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if("0".equals(whUser.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        List<WhUser> list = whUserService.selectWhUserByPCode(whUser.getInvitationCode());//下级
        List<WhUser> sanList = whUserService.selectUserByPPCode(whUser.getInvitationCode());//下下级
        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        Map<String, Object> nextNum = whUserService.getNextUserNum(whUser.getInvitationCode());
        Map<String, Object> nextMoney = whBalancerecordService.getNextMoney(userId);

        Map<String, String> map = new HashMap<>();
        map.put("id", userId);
        map.put("yaoqingNum", String.valueOf(sanList.size()));//三级数量
        map.put("balance", String.valueOf(whUser.getBalance()));//余额
        map.put("first_distrirate", String.valueOf(whUser.getCommission()));//佣金比例
        map.put("second_distirrate", String.valueOf(whUser.getSecondDistirrate()));//二级奖励

        map.put("dayNum", String.valueOf(nextNum.get("dayNum")));//本日拉新
        map.put("monNum", String.valueOf(nextNum.get("monNum")));//本月拉新
        map.put("allNum", String.valueOf(nextNum.get("allNum")));//总拉新

        map.put("dayMoney", String.valueOf(nextMoney.get("dayMoney")));//本日收益
        map.put("monMoney", String.valueOf(nextMoney.get("monMoney")));//本月收益
        map.put("allMoney", String.valueOf(nextMoney.get("allMoney")));//总收益

        return success("操作成功", map);
    }


    /**
     * 下级充值奖励列表  和提现申请记录
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBalancerecord")
    @ResponseBody
    public AjaxResult getBalancerecord(String userId)throws Exception
    {
        WhBalancerecord balancerecord = new WhBalancerecord();
        balancerecord.setUserId(userId);
        List<WhBalancerecord> list = whBalancerecordService.selectWhBalancerecordListByUserId(balancerecord);
        return success("操作成功", list);
    }

    /**
     * 收益明细
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBalancerecordList")
    @ResponseBody
    public AjaxResult getBalancerecordList(String userId)throws Exception
    {
        WhBalancerecord balancerecord = new WhBalancerecord();
        balancerecord.setUserId(userId);
        balancerecord.setOperate("1");
        List<WhBalancerecord> list = whBalancerecordService.selectWhBalancerecordList(balancerecord);

        return success("操作成功", list);
    }

    /**
     * 积分兑换
     * @param userId
     * @param money
     * @param integral
     * @return
     * @throws Exception
     */
    @RequestMapping("/pointsExchange")
    @ResponseBody
    public AjaxResult pointsExchange(String userId, String money, int integral)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if(whUser.getBalance().doubleValue() < Double.valueOf(money)){
            return error("用户余额不足");
        }
        WhUser userP1 = new WhUser();
        userP1.setId(whUser.getId());
        userP1.setIntegral(whUser.getIntegral() + integral);
        userP1.setBalance(new BigDecimal(whUser.getBalance().doubleValue() - Double.valueOf(money)).setScale(2, BigDecimal.ROUND_HALF_UP));
        whUserService.updateWhUser(userP1);

        //积分记录
        WhIntegralHistory history = new WhIntegralHistory();
        history.setId(IdWorker.getId());
        history.setCreateTime(new Date());
        history.setUserId(userId);
        history.setIntegral(integral);
        history.setEventId(null);
        history.setOperat("13");
        whIntegralHistoryService.insertWhIntegralHistory(history);

        WhBalancerecord balancerecord = new WhBalancerecord();
        balancerecord.setId(IdWorker.getId());
        balancerecord.setCreateTime(new Date());
        balancerecord.setUserId(userId);
        balancerecord.setBalance(new BigDecimal(-Double.valueOf(money)).setScale(2, BigDecimal.ROUND_HALF_UP));
        balancerecord.setOperate("5");

        balancerecord.setFront(whUser.getBalance());
        balancerecord.setAfter(userP1.getBalance());
        balancerecord.setIntegral(integral);
        whBalancerecordService.insertWhBalancerecord(balancerecord);

        return success("操作成功");
    }


    /**
     * 用户提现
     * @param userId
     * @param money
     * @param type 提现方式 1微信 2支付宝
     * @return
     * @throws Exception
     */
    @RequestMapping("/userwithdraw")
    @ResponseBody
    public AjaxResult pointsExchange(String userId, String money, String type)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if(whUser.getBalance().doubleValue() < Double.valueOf(money)){
            return error("用户余额不足");
        }
        WhUser userP1 = new WhUser();
        userP1.setId(whUser.getId());
        userP1.setBalance(new BigDecimal(whUser.getBalance().doubleValue() - Double.valueOf(money)).setScale(2, BigDecimal.ROUND_HALF_UP));
        whUserService.updateWhUser(userP1);

        //余额明细
        WhBalancerecord balancerecord = new WhBalancerecord();
        balancerecord.setId(IdWorker.getId());
        balancerecord.setCreateTime(new Date());
        balancerecord.setUserId(userId);
        balancerecord.setBalance(new BigDecimal(-Double.valueOf(money)).setScale(2, BigDecimal.ROUND_HALF_UP));
        balancerecord.setOperate("6");
        balancerecord.setFront(whUser.getBalance());
        balancerecord.setAfter(userP1.getBalance());
        switch (type){
            case "1":
                balancerecord.setType("微信");
                break;
            case "2":
                balancerecord.setType("支付宝");
                break;
        }
        whBalancerecordService.insertWhBalancerecord(balancerecord);

        WhUserwithdraw userwithdraw = new WhUserwithdraw();
        userwithdraw.setId(IdWorker.getId());
        userwithdraw.setUserId(userId);
        userwithdraw.setWithdrawMoney(new BigDecimal(Double.valueOf(money)).setScale(2, BigDecimal.ROUND_HALF_UP));
        switch (type){
            case "1":
                userwithdraw.setWithdrawPic(whUser.getCollectionCodeWx());
                break;
            case "2":
                userwithdraw.setWithdrawPic(whUser.getCollectionCodeZfb());
                break;
        }
        userwithdraw.setStatus("申请");
        userwithdraw.setCreateTime(new Date());
        userwithdraw.setUpdateTime(new Date());
        userwithdraw.setType(type);
        userwithdraw.setWithdrawBefore(whUser.getBalance());
        userwithdraw.setWithdrawAfter(userP1.getBalance());

        whUserwithdrawService.insertWhUserwithdraw(userwithdraw);



        return success("操作成功");
    }

    /**
     * 上传收款码
     * @param type 1微信 2支付宝
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadCollectionCode")
    @ResponseBody
    public AjaxResult uploadCollectionCode(String userId, String imgUrl, String type)throws Exception
    {

        WhUser userP1 = new WhUser();
        userP1.setId(userId);
        switch (type){
            case "1":
                userP1.setCollectionCodeWx(imgUrl);
                break;
            case "2":
                userP1.setCollectionCodeZfb(imgUrl);
                break;
        }
        whUserService.updateWhUser(userP1);

        return success("操作成功");
    }

    /**
     * 获取经验 -- 积分套餐列表
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPointspackage")
    @ResponseBody
    public AjaxResult getPointspackage()throws Exception
    {
       WhPointspackage pointspackage = new WhPointspackage();
        pointspackage.setStatus("启用");
        List<WhPointspackage> list = whPointspackageService.selectWhPointspackageList(pointspackage);
        return success("操作成功", list);

    }

    /**
     * 获取最低的套餐包
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPointsPackageOnce")
    @ResponseBody
    public AjaxResult getPointsPackageOnce()throws Exception
    {
        WhPointspackage pointspackage = new WhPointspackage();
        pointspackage.setStatus("启用");
        List<WhPointspackage> list = whPointspackageService.selectWhPointspackageList(pointspackage);
        return success("操作成功", list.get(0));

    }

    /**
     * 签到成功领取积分
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/signIn")
    @ResponseBody
    public AjaxResult signIn(String userId)throws Exception
    {
        WhIntegralHistory _history = whIntegralHistoryService.getHistoryByUserId(userId);
        if(_history != null){
            return error("今日已签到");
        }

        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");

        WhUser userP = whUserService.selectWhUserById(userId);

        WhUser userP1 = new WhUser();
        userP1.setId(userP.getId());
        userP1.setIntegral(userP.getIntegral() + baseconfig.getDailySend());
        whUserService.updateWhUser(userP1);

        //积分记录
        WhIntegralHistory history = new WhIntegralHistory();
        history.setId(IdWorker.getId());
        history.setCreateTime(new Date());
        history.setUserId(userId);
        history.setIntegral(baseconfig.getDailySend());
        history.setEventId(null);
        history.setOperat("14");
        whIntegralHistoryService.insertWhIntegralHistory(history);

        return success("操作成功");

    }

    /**
     * 获取免费的积分
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFreePoints")
    @ResponseBody
    public AjaxResult getFreePoints(String userId)throws Exception
    {
        WhUser userP = whUserService.selectWhUserById(userId);
        Date nextReceiveTime = userP.getNextReceiveTime();
        if(nextReceiveTime.getTime() > new Date().getTime()){
            return error("免费领取时间未到");
        }
        String level = userP.getLevel();
        WhMemberlevel memberlevel = whMemberlevelService.selectWhMemberlevelById(level);

        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");

        long a = System.currentTimeMillis();
        int b = (int) (memberlevel.getTimeInterval().doubleValue()*60*60*1000);
        a = a + b;
        Date date = new Date(a);
        System.out.println(date);
        WhUser userP1 = new WhUser();
        userP1.setId(userP.getId());
        userP1.setIntegral(userP.getIntegral() + baseconfig.getFreeIntegral());
        userP1.setNextReceiveTime(date);
        whUserService.updateWhUser(userP1);

        //积分记录
        WhIntegralHistory history = new WhIntegralHistory();
        history.setId(IdWorker.getId());
        history.setCreateTime(new Date());
        history.setUserId(userId);
        history.setIntegral(baseconfig.getFreeIntegral());
        history.setEventId(null);
        history.setOperat("15");
        whIntegralHistoryService.insertWhIntegralHistory(history);

        return success("操作成功");

    }

    /**
     * 绑定手机号
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/savePhone")
    @ResponseBody
    public AjaxResult savePhone(String userId, String phone)throws Exception
    {

        WhUser userP = whUserService.selectWhUserById(userId);
        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");


        WhUser user = new WhUser();
        user.setId(userId);
        user.setPhone(phone);
        user.setIntegral(userP.getIntegral() + baseconfig.getRelatePhone());
        whUserService.updateWhUser(user);


        //积分记录
        WhIntegralHistory history = new WhIntegralHistory();
        history.setId(IdWorker.getId());
        history.setCreateTime(new Date());
        history.setUserId(userId);
        history.setIntegral(baseconfig.getRelatePhone());
        history.setEventId(null);
        history.setOperat("16");
        whIntegralHistoryService.insertWhIntegralHistory(history);

        return success("操作成功");

    }


    /**
     * 获取积分记录
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getIntegralHistoryList")
    @ResponseBody
    public AjaxResult getIntegralHistoryList(String userId)throws Exception
    {
        //积分记录
        WhIntegralHistory history = new WhIntegralHistory();
        history.setUserId(userId);

        return success("操作成功", whIntegralHistoryService.selectWhIntegralHistoryList(history));

    }

    /**
     * 获取 疑问解答列表
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAsk")
    @ResponseBody
    public AjaxResult getAsk()throws Exception
    {
        //积分记录
        WhAskquestion askquestion = new WhAskquestion();
        return success("操作成功", whAskquestionService.selectWhAskquestionList(askquestion));

    }


    /**
     * 发送短信验证码
     * @param phone
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/sendMsgCode")
    @ResponseBody
    public AjaxResult bindPhone(String phone)throws Exception {
        String code = commonRpc.sendBatchSms(phone);
        return success("短信发送成功",code);
    }


    /**
     * 获取设置基本参数
     * @return
     * @throws Exception
     */
    @RequestMapping("/getConfig")
    @ResponseBody
    public AjaxResult getConfig()throws Exception
    {

        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");

        return success("操作成功", whzjBaseconfig);
    }


    /**
     * 获取公告内容
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping("/getNotice")
    @ResponseBody
    public AjaxResult getNotice(String type)throws Exception
    {
        SysNotice notice = new SysNotice();
        notice.setNoticeType(type);
        List<SysNotice> list = sysNoticeService.selectNoticeList(notice);
        if(list.size() <= 0){
            return error("暂无公告内容");
        }
        return success("操作成功", list.get(0));
    }

    /**
     * 获取服务器版本号
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getVersion")
    @ResponseBody
    public AjaxResult getVersion(String id)throws Exception
    {
        return success("操作成功", whVersionService.selectWhVersionById(id));
    }

    /**
     * 获取自定义评论内容
     * @param pId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAutocommontByPId")
    @ResponseBody
    public AjaxResult getAutocommontByPId(String pId)throws Exception
    {
        WhAutocommont autocommont = new WhAutocommont();
        autocommont.setPid(pId);
        return success("操作成功", whAutocommontService.selectWhAutocommontList(autocommont));
    }


    /**
     * 邀请数据
     * @param userId
     * @return
     */
    @RequestMapping("/getInvitationData")
    @ResponseBody
    public AjaxResult getInvitationData(String userId)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserById(userId);
        if("0".equals(whUser.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        List<WhUser> list = whUserService.selectWhUserByUserId(userId);//下级
        Map map1 = whIntegralHistoryService.selectIntegralInvitation(userId, "11");
        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        map1.get("integralAll");

        Map<String, Object> map = new HashMap<>();
        map.put("size", list.size());
        map.put("shareSend", baseconfig.getShareSend());
        map.put("list", list);
        map.put("integralAll", map1.get("integralAll"));//邀请获得的积分

        return success("操作成功", map);
    }


    /**
     * 获取系统设置
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBaseConfig")
    @ResponseBody
    public AjaxResult getBaseConfig(String userId)throws Exception
    {
        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        return success("操作成功", baseconfig);
    }


}

